from django.shortcuts import render
# Create your views here.
from django.views import View
from apps.areas.models import Area
from django.http import JsonResponse
from django.core.cache import cache

class ProvinceView(View):
    def get(self,request):
        # 先读取缓存
        # cache.delete('province')
        data_list = cache.get('province')
        #判断缓存是否有数据
        if data_list is None:
            # 1. 查询数据库
            areas = Area.objects.filter(parent__isnull=True)

            data_list = []
            # 2. 将查询结果集遍历 转换为字典数据
            for area in areas:
                data_list.append({
                    'id':area.id,
                    'name':area.name
                })

            # 缓存
            # cache.set(key,value,seconds)
            # 过期时间
            cache.set('province',data_list,24*3600)

        # 3. 返回响应
        return JsonResponse({
            "code":"0",
            "errmsg":"ok",
            "province_list":data_list
        })

class SubAreaView(View):
    def get(self,request,parent_id):

        subs_list = cache.get('city_%s'%parent_id)
        if subs_list is None:
            # 1. 获取 省[市] 的id
            # 2. 根据 省[市] 的id 获取下一级数据
            # 方式一
            # areas = Area.objects.filter(parent_id=parent_id)
            # 方式二
            # 根据 parent_id获取 省 [市]
            pro_city_id = Area.objects.get(id=parent_id)
            areas = pro_city_id.subs.all()

            subs_list = []

            # 3. 将查询结果集便利转换为字典列表
            for area in areas:
                subs_list.append({
                    'id':area.id,
                    'name':area.name
                })

            cache.set('city_%s'%parent_id,subs_list,24*3600)
        # 4. 返回响应
        return JsonResponse({
            "code":"0",
            "errmsg":"OK",
            "sub_data":{
            "subs":subs_list
            }
        })